package com.youbug.mall.seckill.interceptor;

import com.youbug.common.constant.AuthServerConstant;
import com.youbug.common.constant.CartConstant;
import com.youbug.common.to.UmsMemberTo;
import com.youbug.common.to.UserInfoTo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.UUID;

import static com.youbug.common.constant.AuthServerConstant.LOGIN_USER;

public class SeckillInterceptor implements HandlerInterceptor {


    public static ThreadLocal<UmsMemberTo> loginUser = new ThreadLocal<>();

    /***
     * 目标方法执行之前
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        String uri = request.getRequestURI();
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        boolean match = antPathMatcher.match("/mall/seckill/getCurrentSeckillSkus", uri);
        if (match) {
            return true;
        }

        UmsMemberTo attribute = (UmsMemberTo) request.getSession().getAttribute(LOGIN_USER);

        if (attribute != null) {
            //把登录后用户的信息放在ThreadLocal里面进行保存
            loginUser.set(attribute);

            return true;
        } else {
            //未登录，返回登录页面
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();
            out.println("<script>alert('请先进行登录，再进行后续操作！');location.href='http://auth.gulimall.com/mall/login.html'</script>");
            return false;
        }
    }
}
